package com.moon.utils;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;

import android.util.Log;

/**
 * 上传
 * 
 * @author paul
 * @date 2014年5月11日
 */
@Deprecated
public class UploadUtils {

    private static final String TAG                  = UploadUtils.class.getSimpleName();

    public static String upload(String url,String path){
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("title", "主题"));
        params.add(new BasicNameValuePair("content", "内容"));
        try {
            HttpClientUtils.post(url, params);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }
    
    /**
     * 上传图片
     * 
     * @param url
     *            上传地址
     * @param filepath
     *            图片路径
     * @return
     */
    public static String uploadImage(String url, String filepath) {
        try {
        File file = new File(filepath);

        if (!file.exists()) {
            Log.i("leslie", "file not exists");
            return null;
        }

        HttpClient client = new DefaultHttpClient();
        //没解决乱码问题,不行分两次提交
        client.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,"UTF-8");
        HttpPost post = new HttpPost(url);

        FileBody fileBody = new FileBody(file, "image/jpeg");
        MultipartEntity entity = new MultipartEntity();
        // image 是服务端读取文件的 key
        entity.addPart("image", fileBody);
        
        //表单其它内容
        StringBody title = new StringBody("主题");  
        StringBody content = new StringBody("内容");  

        entity.addPart("title", title);
        entity.addPart("content", content);

        post.setEntity(entity);


//        post.getParams().setParameter("title", "主题");
//        post.getParams().setParameter("content", "内容");
//       // post.getParams().setParameter("categoryId", 1L);
//        final List<NameValuePair> params = new ArrayList<NameValuePair>();
//        params.add(new BasicNameValuePair("title", "主题"));
//        params.add(new BasicNameValuePair("content", "内容"));
//        post.
//        post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

       
        
            HttpResponse response = client.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode == 200) {
                String body = EntityUtils.toString(response.getEntity(), "utf-8");
//                ServerResult result = JacksonUtil.fromJSON(body, ServerResult.class);
//                if(result.isResult()){
//                    return "true";
//                }
            }

            return "";
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
    
    
//    public void uploadFileClient(String actionUrl,String uploadFile)
//    {
//      String targetURL = actionUrl;// 上传指定URL
//
//      File targetFile = new File(uploadFile);// 指定上传文件
//      HttpPost httpPost = new HttpPost(targetURL);
//
//      PostMethod filePost = new PostMethod(targetURL);
//      httpPost.getEntity()
//      try
//      {
//
//        // 通过以下方法可以模拟页面参数提交
//        // filePost.setParameter("name", "中文");
//        // filePost.setParameter("pass", "1234");
//        byte[] buffer = new byte[1024];
//        Part[] parts =
//        { new FilePart(targetFile.getName() + System.currentTimeMillis(),
//            targetFile) };
//
//        filePost.setRequestEntity(new MultipartRequestEntity(parts,
//            filePost.getParams()));
//        HttpClient client = new HttpClient();
//        client.getHttpConnectionManager().getParams()
//            .setConnectionTimeout(5000);
//        int status = client.executeMethod(filePost);
//
//        if (status == HttpStatus.SC_OK)
//        {
//          System.out.println("上传成功");
//          // 上传成功
//        } else
//        {
//          System.out.println("上传失败");
//          // 上传失败
//        }
//      } catch (Exception ex)
//      {
//        ex.printStackTrace();
//      } finally
//      {
//        filePost.releaseConnection();
//      }
//
//    }

    
    
    
    
    
   // private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10*1000;   //超时时间
    private static final String CHARSET = "utf-8"; //设置编码
    /**
     * android上传文件到服务器
     * @param file  需要上传的文件
     * @param RequestURL  请求的rul
     * @return  返回响应的内容
     */
    public static String uploadFile(File file,String RequestURL)
    {
        String result = null;
        String  BOUNDARY =  UUID.randomUUID().toString();  //边界标识   随机生成
        String PREFIX = "--" , LINE_END = "\r\n"; 
        String CONTENT_TYPE = "multipart/form-data";   //内容类型
        
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true);  //允许输入流
            conn.setDoOutput(true); //允许输出流
            conn.setUseCaches(false);  //不允许使用缓存
            conn.setRequestMethod("POST");  //请求方式
            conn.setRequestProperty("Charset", CHARSET);  //设置编码
            conn.setRequestProperty("connection", "keep-alive");   
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); 
            
            if(file!=null)
            {
                /**
                 * 当文件不为空，把文件包装并且上传
                 */
                DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 这里重点注意：
                 * name里面的值为服务器端需要key   只有这个key 才可以得到对应的文件
                 * filename是文件的名字，包含后缀名的   比如:abc.png  
                 */
                
                sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END); 
                sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while((len=is.read(bytes))!=-1)
                {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码  200=成功
                 * 当响应成功，获取响应的流  
                 */
                int res = conn.getResponseCode();  
                Log.e(TAG, "response code:"+res);
//                if(res==200)
//                {
                    Log.e(TAG, "request success");
                    InputStream input =  conn.getInputStream();
                    StringBuffer sb1= new StringBuffer();
                    int ss ;
                    while((ss=input.read())!=-1)
                    {
                        sb1.append((char)ss);
                    }
                    result = sb1.toString();
                    Log.e(TAG, "result : "+ result);
//                }
//                else{
//                    Log.e(TAG, "request error");
//                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
